package com.xc.springsecurity.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.springsecurity.mapper.RoleMapper;
import com.xc.springsecurity.mapper.UserMapper;
import com.xc.springsecurity.model.Role;
import com.xc.springsecurity.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if (user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<Role> roles=roleMapper.getRoleByUid(user.getId());
        user.setRoles(roles);
        return user;
    }
}
